package com.woniu.utils;

import com.jcraft.jsch.*;
import java.io.*;

import com.jcraft.jsch.*;
import java.io.*;

public class SftpUtil {

    private static final int SSH_PORT = 22;

    public static void uploadFile(String host, String username, String password,
                                  String localFilePath, String remoteDir) throws JSchException, SftpException {
        Session session = null;
        ChannelSftp channel = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, SSH_PORT);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();

            // 确保远程目录存在
            try {
                channel.cd(remoteDir);
            } catch (SftpException e) {
                channel.mkdir(remoteDir);
                channel.cd(remoteDir);
            }

            // 上传文件
            channel.put(localFilePath, new File(localFilePath).getName());
        } finally {
            if (channel != null) channel.disconnect();
            if (session != null) session.disconnect();
        }
    }

    public static void downloadFile(String host, String username, String password,
                                    String remoteFilePath, String localDir) throws JSchException, SftpException, IOException {
        Session session = null;
        ChannelSftp channel = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, SSH_PORT);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();

            // 确保本地目录存在
            File localDirFile = new File(localDir);
            if (!localDirFile.exists()) localDirFile.mkdirs();

            // 下载文件
            String fileName = new File(remoteFilePath).getName();
            File localFile = new File(localDirFile, fileName);
            channel.get(remoteFilePath, localFile.getAbsolutePath());
        } finally {
            if (channel != null) channel.disconnect();
            if (session != null) session.disconnect();
        }
    }
}